var isDoctorEnd;

function showById(id) {
    $("#" + id).removeClass("hide");
}

function hideById(id) {
    $("#" + id).addClass("hide");
}

function showOverlay() {
    downRefreshState(false);
    $("body").css("overflow", "hidden");
    //$("body").attr("scroll","no");
    showById("overlay");
}

function hideOverlay() {
    downRefreshState(true);
    $("body").css("overflow", "auto");
    //$("body").attr("scroll","auto");
    hideById("overlay");

    $.each(overlayNodeList, function (idx, node) {
        $(node).addClass("hide");
    });
    overlayNodeList.length = 0;
}

var overlayNodeList = [];
function addNodeToOverlay(node) {
    overlayNodeList.push(node);
}


function loginChat() {
    //debugger;
    var imAccount = getCookie("im_patient_account");
    var imPassword = getCookie("im_patient_pwd");

    var imAccountDoc = getCookie("im_doctor_account");
    var imPasswordDoc = getCookie("im_doctor_pwd");

    var imName = getCookie("im_name");
    if (imAccount != null && imAccount != "null") {

        if (activityManager != null) {
            activityManager.login(imAccount, imPassword, imAccountDoc, imPasswordDoc, imName);
        } else if (iOSActionManager != null) {
            debugAlert(iOSActionManager);

            var loginDto = {};
            loginDto.account = imAccount;
            loginDto.pwd = imPassword;

            loginDto.account_doc = imAccountDoc;
            loginDto.pwd_doc = imPasswordDoc;

            loginDto.name = imName;
            iOSActionManager.startLogin(loginDto);
        }
    }
}
setTimeout("loginChat();", 1000);

//$(document).ready(function () {
//    setTimeout("loginChat();", 1000);
//});

var loginDiv = false;
function showLoginDiv(force) {
    if (!loginDiv) {
        loginDiv = true;
        $("body>*").addClass("blur");

        var div = $("<div id='login-in-page-div'>");
        div.load("/login-inpage.html?time=" + new Date().getTime());

        $("body").append(div);
    }
}

function refreshAllPage() {
    var refresh = 1 + (1 << 4) + (1 << 8) + (1 << 12);
    if (activityManager != null) {
        //全部刷新
        activityManager.injectRefreshWebState(refresh);
    } else if (iOSActionManager != null) {
        //全部刷新
        iOSActionManager.injectRefreshWebState(refresh);
    }
}

function refreshService() {
    var refresh = (1 << 8);
    if (activityManager != null) {
        //全部刷新
        activityManager.injectRefreshWebState(refresh);
    } else if (iOSActionManager != null) {
        //全部刷新
        //iOSActionManager.injectRefreshWebState(refresh);
    }
}


function setDoctorEnd() {
    isDoctorEnd = true;

    //if (hasToken()) {
    //    var application_status = getCookie("application_status");
    //
    //    if (application_status == -1) {
    //        alert("请先进行医生认证");
    //        window.location.href = "/doctor/authentication01.html";
    //    }
    //    else if (application_status == 0) {
    //        alert("您的资料正在审核，请耐心等待！");
    //        window.location.href = "/doctor/authentication01.html";
    //    }
    //}
}

function getApplicationStatus(onHasResult) {
    isDoctorEnd = true;

    if (hasToken()) {
        grey_get_profile(function (data) {
            //认证状态
            //-1普通用户 0认证中（第一次认证） 1认证通过 2认证中（重新认证）  -2（认证未通过）
            setCookie("application_status", data.status);

            var application_status = data.status;

            onHasResult(data);

            //return application_status;
        });
    }
}

function checkApplication2() {
    isDoctorEnd = true;

    if (hasToken()) {
        grey_get_profile(function (data) {
            //认证状态
            //-1普通用户 0认证中（第一次认证） 1认证通过 2认证中（重新认证）
            setCookie("application_status", data.status);

            var application_status = data.status;

            if (application_status == -1) {
                showAlert(doctor_auth_msg);
                window.location.href = "/doctor/authentication01.html";
            }
            else if (application_status == 0) {
                alert("您的资料正在审核，请耐心等待！");
                window.location.href = "/doctor/authentication01.html";
            }
        });
    }
}

function addStartChatToButton(button, order) {

}

function selectImg(self, event) {
    uploadImg(self, event, true, 100, 600, 600, false);
}

function selectAvatar(self, event) {
    if (!hasToken()) {
        showLoginDiv();
        return;
    }

    uploadImg(self, event, true, 100, 300, 300, true);
}

/**
 * 压缩上传
 *
 * @param self 图片资源
 * @param event 图片接收控件对象
 * @param compression 是否压缩
 * @param compressionRatio 压缩比(小于100的数字,默认100，不压缩质量)
 * @param maxWidth 最大宽(默认600px)
 * @param maxHeight 最大高(默认600px)
 * @param spilt 是否裁切(默认是false)
 */
function uploadImg(self, event, compression, compressionRatio, maxWidth, maxHeight, spilt) {

    if (compression == null) {
        if (maxHeight != null || maxHeight != null || (compressionRatio != null && compression != 100)) {
            compression = true;
        }
    }

    compressionRatio = compressionRatio == null ? 100 : compressionRatio;
    maxWidth = maxWidth == null ? 600 : maxWidth;
    maxHeight = maxHeight == null ? 600 : maxHeight;
    spilt = spilt == null ? false : spilt;

    var versionCode = getAppVersionCode();

    if (activityManager != null) {
        if (versionCode <= '000000090000') {
            activityManager.uploadImg(self, compression, maxWidth, maxHeight, spilt, "1");
        } else {
            var remark = {};
            remark.compressionRatio = compressionRatio;
            activityManager.uploadImg(self, compression, maxWidth, maxHeight, spilt, "1", JSON.stringify(remark));
        }
    } else if (iOSActionManager != null) {
        if (versionCode <= '000000090000') {
            iOSActionManager.uploadAvatarImg(self, compression, maxWidth, maxHeight, spilt, "1");
        } else {
            var remark = {};
            remark.compressionRatio = compressionRatio;
            iOSActionManager.uploadAvatarImg(self, compression, maxWidth, maxHeight, spilt, "1", JSON.stringify(remark));
        }
    } else {
        $(event).click();
    }

}

function getAppVersionCode() {
    var appVersion = null;

    try {
        if (activityManager != null) {
            appVersion = activityManager.getVersion();
        } else if (iOSActionManager != null) {
            appVersion = iOSActionManager.getVersion();
        } else {
            debugAlert("纯网页，给0.0.0的版本返回");
            return '000000000000';
        }


        if (appVersion == null || appVersion == '') {
            debugAlert("未能正确获取版本");
            return '000000000000';
        }

        appVersion = appVersion.split('_')[0];

        var appVersionCodeArray = appVersion.split('.');

        if (appVersionCodeArray.length != 3) {
            debugAlert("未能正确获取版本,appVersion>>" + appVersion);
            return '000000000000';
        }

        var zeroArray = [];
        zeroArray[0] = '0000';
        zeroArray[1] = '000';
        zeroArray[2] = '00';
        zeroArray[3] = '0';
        zeroArray[4] = '';

        var newCode = '';
        newCode += appVersionCodeArray[0] == 0 ? '0000' : zeroArray[appVersionCodeArray[0].length] + appVersionCodeArray[0];
        newCode += appVersionCodeArray[1] == 0 ? '0000' : zeroArray[appVersionCodeArray[1].length] + appVersionCodeArray[1];
        newCode += appVersionCodeArray[2] == 0 ? '0000' : zeroArray[appVersionCodeArray[2].length] + appVersionCodeArray[2];
        return newCode;

    } catch (e) {
        debugAlert('获取版本出现异常:' + e);
        return '000000000000';
    }


}

function preview(file, target) {
    var reader = new FileReader();//创建FileReader对象
    var img = $(target);
    reader.onload = function (e) {
        img.attr("src", e.target.result);

    };
    reader.readAsDataURL(file);
}

function onFileChange(e, target) {
    var file = e.files[0],//事件目标
        val = $(e).val();

    var id = $(e).attr("idx");

    if (val != null && val != "") {
        preview(file, $(target));
    }
}

function uploadImgDone(target, url) {
    var t = $(target);
    t.attr("src", url);
}

var latitude = null;
var longitude = null;

function setLocation(_longitude, _latitude) {
    longitude = _longitude;
    latitude = _latitude;
}

function getLocationInfo() {
    if (activityManager != null) {
        activityManager.getLocationInfo();
    } else if (iOSActionManager != null) {
        iOSActionManager.getLocationInfo();
    }
}

var medicalClient = false;

function changeTwoDecimal(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        //alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    f_x = Math.round(f_x * 10) / 10;

    return f_x;
}

var testMobileList = ["18675573369", "13926575115", "15507545208", "18925281957", "15172546511", "18927440140", "15914109271", "15978877988", "18682060681", "18064099920"];

function isTestMode() {
    var mobile = getCookie("mobile");
    if (mobile == null || mobile == "") {
        return false;
    } else {
        for (var i = 0; i < testMobileList.length; i++) {
            if (testMobileList[i] == mobile) {
                return true;
            }
        }
        //return false;
    }
    return false;
}

function setCity(cityName) {
    setCookie("city_name", cityName);
    setCookie("city", null);
    grey_get_city(cityName, function (data) {
        setCookie("city", data.id);
    }, function (data) {

    });
}

function retryToGetCity() {
    var id = getCookie("city");
    var name = getCookie("city_name");

    if (id == null || id == "") {
        if (name != null) {
            grey_get_city_sync(name, function (data) {
                debugger;

                if (data.id == null || data.id == "") {

                    setCookie("city", "--");

                } else {
                    setCookie("city", data.id);
                    id = data.id;
                }
            }, function (data) {

            });
        }
    }
}



var defaultCityId = 231;

function getCityId() {
    var id = getCookie("city");
    var res = null;
    if (id == null || id == "") {
        return 236;
    } else {
        var _id = parseInt(id);
        if (_id == null || _id == "") {
            return 236;
        } else {
            return _id;
        }
    }
}

function setAppId(appId) {
    setCookie("app_id", appId);
}

function changeTwoDecimal(x) {
    var f_x = x.toString();
    var length = f_x.length;
    var idx = f_x.indexOf(".");

    if (idx > 0) {
        var l = idx + 3;
        l = l > length ? length : l;

        return f_x.substring(0, l);
    }
    return f_x;
}

var unload = false;


function initForAllPages() {
    document.body.onbeforeunload = function (event) {
        unload = true;

    };
}


function compareVersion(va, vb) {
    var vas = va.split(".");
    var vbs = vb.split(".");
    if (vas.length != 3) {
        return -1;
    }
    if (vbs.length != 3) {
        return 1;
    }

    for (var i = 0; i < 3; i++) {
        if (parseInt(vas[i]) > parseInt(vbs[i])) {
            return 1;
        } else if (parseInt(vas[i]) < parseInt(vbs[i])) {
            return -1;
        }
    }
    return 0;
}

function getVersion() {
    var verInfo;

    if (null != activityManager) {
        verInfo = activityManager.getVersion();
    }
    return verInfo;
}

function Achat(order) {
    grey_get_order_info(order.id, function (data) {
        var order = data.order_info;
        order.description = JSON.parse(order.description);

        //var totalTime = order.total_dose;
        //if (order.appoint_end_time < new Date().getTime()) {
        //    alert("已超过预约时间，不能再发起视频咨询！");
        //    return;
        //}
        //if (order.used_dose != null) {
        //    totalTime = order.total_dose - order.used_dose;
        //    if (totalTime <= 0) {
        //        alert("该订单已经使用完毕！");
        //        refresh();
        //        return;
        //    }
        //}

        chat(order);

    });


    //chat(order);
}


function AvideoChat(orderId) {
    grey_get_order_info(orderId, function (data) {
        var order = data.order_info;
        order.description = JSON.parse(order.description);


        var totalTime = order.total_dose;
        if (order.appoint_end_time < new Date().getTime()) {
            alert("已超过预约时间，不能再发起视频咨询！");
            return;
        }
        if (order.used_dose != null) {
            totalTime = order.total_dose - order.used_dose;
            if (totalTime <= 0) {
                alert("该订单已经使用完毕！");
                refresh();
                return;
            }
        }

        chat(order);

    });
}

function onPageFocus() {

}

function onPageBlur() {

}

function buildNoPrescriptionHospitalization(hospitalization) {
    var paBlock = $("\
                    <div class='pa-block block'>\
                        <div class='line'>\
                            <div class='pa-title'>\
                                <span class='pa-label'>住院号：</span>\
                                <span class='hos-num'></span>\
                            </div>\
                            <div class='pa-title fright'>\
                                <span class='pa-label'>入院日期：</span>\
                                <span class='check-in-date'></span>\
                            </div>\
                        </div>\
                        <div class='line'>\
                            <div class='pa-bed-no'>\
                                <span class='pa-bed-num'></span>\
                                <span class='pa-bed-str'>床</span>\
                            </div>\
                            <div class='pa-info'>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>姓名：</div>\
                                    <div class='pa-value pa-name'></div>\
                                    <div class='pa-value pa-age'></div>\
                                    <div class='pa-value pa-sex'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>特殊说明：</div>\
                                    <div class='pa-value diagnose'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <span class='pa-label'>治疗项目：</span>\
                                    <span class='pa-value treatment-groups'>未安排</span>\
                                </div>\
                            </div>\
                        </div>\
                        <div class='line pa-buttons'>\
                            <div class='pa-button'>安排治疗</div>\
                        </div>\
                    </div>\
            ");

    paBlock.find(".hos-num").text(hospitalization.hos_num);
    paBlock.find(".check-in-date").text(new Date(hospitalization.check_in_time).format("yyyy-MM-dd"));
    paBlock.find(".pa-bed-no .pa-bed-num").text(hospitalization.bed.num);
    paBlock.find(".pa-name").text(hospitalization.patient.name);
    paBlock.find(".pa-sex").text(hospitalization.patient.sex == "male" ? "男" : "女");

    paBlock.find(".pa-age").text(new Date().getYear() - new Date(hospitalization.patient.birthday).getYear() + "岁");
    var diagnose = JSON.parse(hospitalization.diagnose);
    var diagnoseText = "";
    $.each(diagnose, function (idx, val) {
        diagnoseText = diagnoseText + val + " ";
    });
    paBlock.find(".diagnose").text(diagnoseText);

    //TODO 添加整块点击事件
    paBlock.bind('click', function (event) {
        window.location.href = "/doctor/patient-record.html?hospitalization_id=" + hospitalization.id + "&editable=false&action=doctor_look_up&right_button=编辑";
    });
    paBlock.find(".pa-button").bind('click', function (event) {
        event.stopPropagation();
        window.location.href = "/doctor/patient-record.html?hospitalization_id=" + hospitalization.id + "&editable=false&action=set_prcp";
    });

    return paBlock;
}

function buildExistPrescriptionHospitalization(hospitalization) {
    var paBlock = $("<div class='block pa-block'>\
                        <div class='line pa-title pa-name'>\
                            <span class='pa-label'>姓名：</span>\
                            <span class='pa-value pa-name-value'>张三</span>\
                        </div>\
                        <div class='line pa-title check-in-date'>\
                            <span class='pa-label check-in-date-label'>入院日期：</span>\
                            <span class='pa-value check-in-date-value'>2016-01-02</span>\
                        </div>\
                        <div class='line pa-detail'>\
                            <div class='pa-note'>\
                                <div class='age-sex'>\
                                    <span class='pa-label'>年龄：</span>\
                                    <span class='pa-value pa-age'>36岁</span>\
                                </div>\
                                <div class='age-sex'>\
                                    <span class='pa-label'>性别：</span>\
                                    <span class='pa-value pa-sex'>女</span>\
                                </div>\
                            </div>\
                            <div class='pa-note'>\
                                <span class='pa-label'>住院号：</span>\
                                <span class='pa-value hos-num'></span>\
                            </div>\
                            <div class='pa-note'>\
                                <span class='pa-label'>特殊说明：</span>\
                                <span class='pa-value diagnose'></span>\
                            </div>\
                            <div class='pa-note'>\
                                <span class='pa-label'>治疗项目：</span>\
                                <span class='pa-value treatment-groups'>TODO</span>\
                            </div>\
                        </div>\
                        <div class='pa-bed-no'>\
                            <span class='pa-bed-num'></span>\
                            <span class='pa-bed-str'>床</span>\
                        </div>\
                    </div>\
            ");

    paBlock.find(".hos-num").text(hospitalization.hos_num);
    paBlock.find(".check-in-date-value").text(new Date(hospitalization.check_in_time).format("yyyy-MM-dd"));
    paBlock.find(".pa-bed-no .pa-bed-num").text(hospitalization.bed.num);
    paBlock.find(".pa-name-value").text(hospitalization.patient.name);
    paBlock.find(".pa-age").text(new Date().getYear() - new Date(hospitalization.patient.birthday).getYear() + "岁");
    paBlock.find(".pa-sex").text(hospitalization.patient.sex == "male" ? "男" : "女");
    var diagnose = JSON.parse(hospitalization.diagnose);
    var diagnoseText = "";
    $.each(diagnose, function (idx, val) {
        diagnoseText = diagnoseText + val + " ";
    });
    paBlock.find(".diagnose").text(diagnoseText);
    var groupMap = [];
    if (hospitalization.prescription != null) {
        $.each(hospitalization.prescription.prescription_items, function (idx, val) {
            var groupName = val.item.treatment_group.name;
            groupMap.push(groupName);
        });
    }
    groupMap = groupMap.unique();
    var groupStr = "";
    //debugger;
    $.each(groupMap, function (idx, prop) {
        //debugAlert(Object.keys(groupMap).length);
        //debugAlert(idx);
        if (idx != groupMap.length - 1) {
            groupStr += prop + "/";
        } else {
            groupStr += prop;
        }
    });

    paBlock.find(".treatment-groups").text(groupStr);

    //TODO 添加整块点击事件
    paBlock.bind('click', function () {
        window.location.href = "/doctor/patient-record.html?hospitalization_id=" + hospitalization.id + "&editable=false&action=check_out&right_button=编辑";
    });
    return paBlock;
}


function buildNoTherapistHospitalization(hospitalization) {
    var paBlock = $("\
                    <div class='pa-block block'>\
                        <div class='line'>\
                            <div class='pa-title'>\
                                <span class='pa-label'>住院号：</span>\
                                <span class='hos-num'></span>\
                            </div>\
                            <div class='pa-title fright'>\
                                <span class='pa-label'>入院日期：</span>\
                                <span class='check-in-date'></span>\
                            </div>\
                        </div>\
                        <div class='line'>\
                            <div class='pa-bed-no'>\
                                <span class='pa-bed-num'></span>\
                                <span class='pa-bed-str'>床</span>\
                            </div>\
                            <div class='pa-info'>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>姓名：</div>\
                                    <div class='pa-value pa-name'></div>\
                                    <div class='pa-value pa-age'></div>\
                                    <div class='pa-value pa-sex'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>特殊说明：</div>\
                                    <div class='pa-value diagnose'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <span class='pa-label'>治疗项目：</span>\
                                    <span class='pa-value treatment-groups'>TODO</span>\
                                </div>\
                            </div>\
                        </div>\
                        <div class='line pa-buttons'>\
                            <div class='pa-button'>安排治疗师</div>\
                        </div>\
                    </div>\
            ");

    paBlock.find(".hos-num").text(hospitalization.hos_num);
    paBlock.find(".check-in-date").text(new Date(hospitalization.check_in_time).format("yyyy-MM-dd"));
    paBlock.find(".pa-bed-no .pa-bed-num").text(hospitalization.bed.num);
    paBlock.find(".pa-name").text(hospitalization.patient.name);
    paBlock.find(".pa-sex").text(hospitalization.patient.sex == "male" ? "男" : "女");

    paBlock.find(".pa-age").text(new Date().getYear() - new Date(hospitalization.patient.birthday).getYear() + "岁");
    var diagnose = JSON.parse(hospitalization.diagnose);
    var diagnoseText = "";
    $.each(diagnose, function (idx, val) {
        diagnoseText = diagnoseText + val + " ";
    });
    paBlock.find(".diagnose").text(diagnoseText);

    var groupMap = [];
    if (hospitalization.prescription != null) {
        $.each(hospitalization.prescription.prescription_items, function (idx, val) {
            var groupName = val.item.treatment_group.name;
            groupMap.push(groupName);
        });
    }
    groupMap = groupMap.unique();
    var groupStr = "";
    $.each(groupMap, function (idx, prop) {
        if (idx != groupMap.length - 1) {
            groupStr += prop + "/";
        } else {
            groupStr += prop;
        }
    });
    paBlock.find(".treatment-groups").text(groupStr);

    paBlock.find(".pa-button").bind('click', function () {
        event.stopPropagation();
        window.location.href = "/doctor/patient-record.html?hospitalization_id=" + hospitalization.id + "&editable=false&action=set_therapist";
    });
    //TODO 添加整块点击事件
    paBlock.bind('click', function () {
        window.location.href = "/doctor/patient-record.html?hospitalization_id=" + hospitalization.id + "&editable=false&action=therapist_leader_look_up";
    });

    return paBlock;
}

function buildExistTherapistHospitalization(hospitalization) {
    var paBlock = $("\
                    <div class='pa-block block'>\
                        <div class='line'>\
                            <div class='pa-title'>\
                                <span>住院号：</span>\
                                <span class='hos-num'></span>\
                            </div>\
                            <div class='pa-title fright'>\
                                <span>入院日期：</span>\
                                <span class='check-in-date'></span>\
                            </div>\
                        </div>\
                        <div class='line'>\
                            <div class='pa-bed-no'>\
                                <span class='pa-bed-num'></span>\
                                <span class='pa-bed-str'>床</span>\
                            </div>\
                            <div class='pa-info'>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>姓名：</div>\
                                    <div class='pa-value pa-name'></div>\
                                    <div class='pa-value pa-age'></div>\
                                    <div class='pa-value pa-sex'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>特殊说明：</div>\
                                    <div class='pa-value diagnose'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <span class='pa-label'>治疗项目：</span>\
                                    <span class='pa-value treatment-groups'>TODO</span>\
                                </div>\
                            </div>\
                        </div>\
                        <div class='line'>\
                            <div class='pa-bottom'>\
                                <span class='pa-label'>治疗师：</span>\
                                <span class='pa-value therapist-name'></span>\
                            </div>\
                        </div>\
                    </div>\
            ");

    paBlock.find(".hos-num").text(hospitalization.hos_num);
    paBlock.find(".check-in-date").text(new Date(hospitalization.check_in_time).format("yyyy-MM-dd"));
    paBlock.find(".pa-bed-no .pa-bed-num").text(hospitalization.bed.num);
    paBlock.find(".pa-name").text(hospitalization.patient.name);
    paBlock.find(".pa-sex").text(hospitalization.patient.sex == "male" ? "男" : "女");

    paBlock.find(".pa-age").text(new Date().getYear() - new Date(hospitalization.patient.birthday).getYear() + "岁");
    var diagnose = JSON.parse(hospitalization.diagnose);
    var diagnoseText = "";
    $.each(diagnose, function (idx, val) {
        diagnoseText = diagnoseText + val + " ";
    });
    paBlock.find(".diagnose").text(diagnoseText);

    var groupMap = [];
    if (hospitalization.prescription != null) {
        $.each(hospitalization.prescription.prescription_items, function (idx, val) {
            var groupName = val.item.treatment_group.name;
            groupMap.push(groupName);
        });
    }
    groupMap = groupMap.unique();
    var groupStr = "";
    $.each(groupMap, function (idx, prop) {
        if (idx != groupMap.length - 1) {
            groupStr += prop + "/";
        } else {
            groupStr += prop;
        }
    });
    paBlock.find(".treatment-groups").text(groupStr);

    paBlock.find(".therapist-name").text(hospitalization.prescription.prescription_items[0].therapist.name);
    //TODO 添加整块点击事件
    paBlock.bind('click', function () {
        window.location.href = "/doctor/treatment_patient_detail.html?editable=false&patient_id=" + hospitalization.patient.id + "&medical_name=" + hospitalization.medical.name + "&edit_page=0&prcp_id=" + hospitalization.prescription.id + "&patient_name=" + hospitalization.patient.name + "&hospitalization_id=" + hospitalization.id + "&title=患者信息|治疗安排表" + "&action=look_up_exist_therapist&right_button=编辑";
    });

    return paBlock;
}


function buildThePres(hospitalization) {
    var paBlock = $("\
                    <div class='pa-block block'>\
                        <div class='line'>\
                            <div class='pa-title'>\
                                <span class='pa-label'>住院号：</span>\
                                <span class='hos-num'></span>\
                            </div>\
                            <div class='pa-title fright'>\
                                <span class='pa-label'>入院日期：</span>\
                                <span class='check-in-date'></span>\
                            </div>\
                        </div>\
                        <div class='line'>\
                            <div class='pa-bed-no'>\
                                <span class='pa-bed-num'></span>\
                                <span class='pa-bed-str'>床</span>\
                            </div>\
                            <div class='pa-info'>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>姓名：</div>\
                                    <div class='pa-value pa-name'></div>\
                                    <div class='pa-value pa-age'></div>\
                                    <div class='pa-value pa-sex'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <div class='pa-label'>特殊说明：</div>\
                                    <div class='pa-value diagnose'></div>\
                                </div>\
                                <div class='pa-note'>\
                                    <span class='pa-label'>治疗项目：</span>\
                                    <span class='pa-value treatment-groups'>TODO</span>\
                                </div>\
                            </div>\
                        </div>\
                        <div class='line pa-buttons'>\
                            <div class='pa-button'></div>\
                        </div>\
                    </div>\
            ");
    paBlock.find(".hos-num").text(hospitalization.hos_num);
    paBlock.find(".check-in-date").text(new Date(hospitalization.check_in_time).format("yyyy-MM-dd"));

    //paBlock.find(".pa-bed-no").text(hospitalization.bed.num);
    paBlock.find(".pa-bed-no .pa-bed-num").text(hospitalization.bed.num);
    paBlock.find(".pa-name").text(hospitalization.patient.name);
    paBlock.find(".pa-sex").text(hospitalization.patient.sex == "male" ? "男" : "女");

    paBlock.find(".pa-age").text(new Date().getYear() - new Date(hospitalization.patient.birthday).getYear());
    if (hospitalization.diagnose != null) {
        var diagnose = JSON.parse(hospitalization.diagnose);
        var diagnoseText = "";
        $.each(diagnose, function (idx, val) {
            diagnoseText = diagnoseText + val + " ";
        });
        paBlock.find(".diagnose").text(diagnoseText);
    }


    var treatmentGroupsText = "";
    //$.each(hospitalization.prescription.item_groups,function(idx,val) {
    //    treatmentGroupsText = treatmentGroupsText + val + "\\";
    //});

    if (hospitalization.prescription != null && hospitalization.prescription.prescription_items != null) {
        $.each(hospitalization.prescription.prescription_items, function (idx, prescription_item) {
            if (treatmentGroupsText.indexOf(prescription_item.item.treatment_group.name) == -1) {
                treatmentGroupsText = treatmentGroupsText + prescription_item.item.treatment_group.name + "\\";
            }
        });
    }

    if (treatmentGroupsText.length != 0) {
        treatmentGroupsText = treatmentGroupsText.substr(0, treatmentGroupsText.length - 1);
    }

    paBlock.find(".treatment-groups").text(treatmentGroupsText);

    if (myGroupId == null) {
        loadMyTreatGroup();
    }

    paBlock.find(".pa-button").text("安排治疗");

    if (hospitalization.prescription != null && hospitalization.prescription.prescription_items != null) {
        for (var i = 0; i < hospitalization.prescription.prescription_items.length; i++) {
            if (hospitalization.prescription.prescription_items[i].item.treatment_group.id == myGroupId) {
                if (hospitalization.prescription.prescription_items[i].start_time != null) {
                    paBlock.find(".pa-button").text("重新安排");
                    break;
                }
            }
        }
    }

    //var clickArrange=false;

    //TODO 添加内容
    paBlock.find(".treatment-groups");
    paBlock.find(".therapist-name");
    //TODO 添加整块点击事件
    paBlock.bind('click', function () {
        //if(!clickArrange) {
        //window.location.href="/doctor/patient-record.html?editable=false&hospitalization_id="+hospitalization.id+"&action=set_treatment_finish";
        var title = "患者信息|治疗安排表";
        if (paBlock.find(".pa-button").text() == "安排治疗") {
            title = "患者信息";
        }
        window.location.href = "/doctor/treatment_patient_detail.html?editable=false&patient_id=" + hospitalization.patient.id + "&medical_name=" + hospitalization.medical.name + "&edit_page=1&prcp_id=" + hospitalization.prescription.id + "&patient_name=" + hospitalization.patient.name + "&hospitalization_id=" + hospitalization.id + "&title=" + title + "&action=set_treatment_finish";
        //}
    });

    paBlock.find(".pa-button").bind('click', function () {
        //clickArrange=true;
        event.stopPropagation();
        window.location.href = "/doctor/treatment_arrange_time.html?patient_id=" + hospitalization.patient.id + "&patient_name=" + encodeURI(hospitalization.patient.name);
    });

    return paBlock;
}

function setPageTitle(title) {
    if (iOSActionManager != null) {
        iOSActionManager.setNavTitle(title);
    }
    $("title").text(title);
}

function setPageCache(key, value) {
    if (activityManager != null) {
        activityManager.putPageCache(key,value);
    }
    else if (iOSActionManager != null) {
        //alert("title_idx : " + value);
        iOSActionManager.putPageCache(key,value);
    }
    else {
        localStorage.setItem(key,value);
    }
}
function getPageCache(key) {
    if (activityManager != null) {
        return activityManager.getPageCache(key);
    }
    else if (iOSActionManager != null) {
        //return iOSActionManager.getPageCache(key);
        return null;
    }
    else {
        //return localStorage.getItem(key);
        return null;
    }
}

function addDefaultOption(root,text) {
    var option = $("<option>");
    option.attr("disabled","disabled");
    option.attr("selected","selected");

    option.text(text);


    root.append(option);
}

function addOption(root,val,text) {
    var option = $("<option>");
    option.attr("value",val);
    option.text(text);

    root.append(option);
}

var pageStack = [];
var pageIdx = 0;

function jsPageAddStack(url,type) {
    //获取cookie中的pageStack
    pageStack = getCookie("pageStack");

    pageStack = (pageStack == null || pageStack == "" || typeof(pageStack) == 'undefined' || pageStack == 'null') ? [] : jQuery.parseJSON(pageStack.toString());
    //pageStack长度
    pageIdx = pageStack.length;
    var node = {};
    node.url = url;
    node.params = $.parseURL2JSON(window.location.search);
    node.type = type;
    var node_url = node.url;
    var node_params = JSON.stringify(node.params);
    var node_type = node.type;
    //如果pageStack为空或传入的url地址,参数,标题与pageStack最后项的url地址,参数,标题不同,则视为是进入新界面
    if (pageIdx) {
	var page_url = pageStack[pageIdx - 1].url,
    	    page_params = JSON.stringify(pageStack[pageIdx - 1].params),
    	    page_type = pageStack[pageIdx - 1].type;
	var is_new_url = (page_url == node_url);
	var is_new_params = (page_params == node_params);
	var is_new_type = (page_type == node_type);
	var isNew = (is_new_url && is_new_params && is_new_type);
    }

    if(pageIdx < 1 || !isNew) {
	//给pageStack添加新值
        pageStack[pageIdx] = node;
        //pageStack长度增加
        pageIdx++;
    }

}

function jsGoBack(step) {
    if(pageIdx < 2) {
        //debugAlert("now page idx is " + pageIdx);
        return;
    } else {
        var pageStackTemp = [];
        pageIdx = (null == step || typeof (step) != 'number') ? (pageIdx - 2) : (pageIdx - step - 1);
        for(var i=0; i<=pageIdx; i++){
            pageStackTemp.push(pageStack[i]);
        }
        pageStack = pageStackTemp;
        setCookie("pageStack", JSON.stringify(pageStack));
        var node = pageStack[pageIdx];
        //pageIdx = pageIdx - 1;
        if("params" in node) {
            setParamToUrl(node.params);
        }
        if(node.type == "title") {
            loadTitle(node.url);
        } else if(node.type == "content") {
            loadContent(node.url);
        }
    }
}

var urlIdMap = {
    homepage: "li_doctor_home",
    //report: "report_report",
    transfer: "transfer",
    evaluation_prcp_list: "prcp_evaluation_prcp_list",
    training_prcp_list: "prcp_training_prcp_list",
    D_therapist_scheduling:"D_therapist_scheduling",
    config: "system_config",
    homepage_therapist: "li_therapist_home",
    all_emr_list: "emr_all_emr_list",
    evaluation_prcp_by_therapist_list: "prcp_evaluation_prcp_by_therapist_list",
    therapist_scheduling: "scheduling_therapist_scheduling",
    therapist_group_scheduling: "scheduling_therapist_group_scheduling"
};

function createTitleNav(title){
    //设置pageStack末尾组件的title
    pageStack[pageIdx - 1].title = title;
    //pageStack存入cookie
    setCookie("pageStack", JSON.stringify(pageStack));
    //定义导航栏
    var ol = $("ol[class='breadcrumb']");
    //先清空导航栏内容
    ol.empty();
    //重新生成导航栏
    for (var i = 0; i < pageIdx - 1; i++) {
        var li = $("<li>");
        var a;
        
        var key = pageStack[i].url.split("/")[2].split(".")[0];
        //要导入的正文的文件名
        key = key.substring(0, key.length-6);
        //定义导航元素的单击事件
        if(urlIdMap[key] != null){
            //如果urlMap中能匹配到,则激活匹配到的元素的单击事件
            a = $("<a onclick='$(\"#" + urlIdMap[key] + "\").click();'>");
        } else {
            //如果urlMap中没有匹配到,则定义单击事件为JSGoBack
            a = $("<a onclick='jsGoBack(" + (pageIdx - 1 - i) + ")'>");
        }
        //导航元素的文本
        a.text(pageStack[i].title);
        li.append(a);
        ol.append(li);
    }
    if(pageIdx < 2){
        return;
    }
    var li = $("<li>");
    var a = $("<a>");
    a.text(pageStack[pageIdx-1].title);
    li.append(a);
    ol.append(li);

    for (var i = pageIdx-1; i >= 0; i--){
        var key = pageStack[i].url.split("/")[2].split(".")[0];
        //要导入的正文的文件名
        key = key.substring(0, key.length-6);
        //匹配的导航元素的Id
        var id = urlIdMap[key];
        //设置导航菜单的图标
        if(id != null){
            console.log("oldImg3", id);
            var currentLi = $("#" + id);
            //如果匹配到的导航菜单元素不是选中状态
            if(!currentLi.hasClass('active')) {
                var oldLi = $("#side-menu li.active");
                //获取img的src地址
                var oldImg = oldLi.children("a").children("div").children("img").attr("src");
                //替换图片地址,替换掉白色图片
                oldImg = oldImg.replace("-white", "");
                //替换图片
                oldLi.children("a").children("div").children("img").attr("src", oldImg);
                //获取替换后的图片地址
                oldImg = currentLi.children("a").children("div").children("img").attr("src");
                console.log("oldImg1", oldImg);
                //如果新图片地址不是#
                if (oldImg != '#') {
                    //替换成白色图片地址
                    oldImg = oldImg.substring(0, oldImg.indexOf(".")) + "-white" + oldImg.substring(oldImg.indexOf("."), oldImg.length);
                    console.log("oldImg2", oldImg);
                    //替换图片
                    currentLi.children("a").children("div").children("img").attr("src", oldImg);
                }
                //取消原选中元素的选中状态
                oldLi.removeClass("active");
                //激活匹配到的导航菜单元素选中状态
                currentLi.addClass("active");
            }
            break;
        }
    }

}
//
//function jsGoForward() {
//
//}


function openGauge(itemId){
    addParamToUrl({"prcp_item_id":itemId});
    loadTitle("/gauge/gauge_title.html");
}

function resetModal(event) {
    var md = $(event).parents(".modal-dialog");
    var inputs = md.find("input");
    inputs.val("");
    inputs.prop("checked",false);
    inputs.prop("selected",false);
}

function formatTime(date_time) {
//        //定义星期
//        var week;
//        //switch判断
//        switch (date_time.getDay()){
//            case 1: week="星期一"; break;
//            case 2: week="星期二"; break;
//            case 3: week="星期三"; break;
//            case 4: week="星期四"; break;
//            case 5: week="星期五"; break;
//            case 6: week="星期六"; break;
//            default:week="星期天"; break;
//        }

    //年
    var year = date_time.getFullYear();
    //判断小于10，前面补0
    if (year < 10) {
        year = "0" + year;
    }

    //月
    var month = date_time.getMonth() + 1;
    //判断小于10，前面补0
    if (month < 10) {
        month = "0" + month;
    }

    //日
    var day = date_time.getDate();
    //判断小于10，前面补0
    if (day < 10) {
        day = "0" + day;
    }

    //时
    var hours = date_time.getHours();
    //判断小于10，前面补0
    if (hours < 10) {
        hours = "0" + hours;
    }

    //分
    var minutes = date_time.getMinutes();
    //判断小于10，前面补0
    if (minutes < 10) {
        minutes = "0" + minutes;
    }

    //秒
    var seconds = date_time.getSeconds();
    //判断小于10，前面补0
    if (seconds < 10) {
        seconds = "0" + seconds;
    }

    //拼接年月日时分秒
    var date_str = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

    return date_str;
}


function getHHmm(date_time) {

    //时
    var hours = date_time.getHours();
    //判断小于10，前面补0
    if (hours < 10) {
        hours = "0" + hours;
    }

    //分
    var minutes = date_time.getMinutes();
    //判断小于10，前面补0
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
//
//        //秒
//        var seconds = date_time.getSeconds();
//        //判断小于10，前面补0
//        if (seconds < 10) {
//            seconds = "0" + seconds;
//        }

    //拼接年月日时分秒
    var date_str = hours + ":" + minutes;

    return date_str;
}

function formatDate(date_time) {


    //年
    var year = date_time.getFullYear();
    //判断小于10，前面补0
    if (year < 10) {
        year = "0" + year;
    }

    //月
    var month = date_time.getMonth() + 1;
    //判断小于10，前面补0
    if (month < 10) {
        month = "0" + month;
    }

    //日
    var day = date_time.getDate();
    //判断小于10，前面补0
    if (day < 10) {
        day = "0" + day;
    }


    //拼接年月日时分秒
    var date_str = year + "-" + month + "-" + day;

    return date_str;
}
